<template>
  <NEl class="p-4 top-box">
    <div class="fs-2">留言板</div>

    <div>
      <NSpace>
        <NInput v-model:value="queryInfo.info" placeholder="标题搜索"></NInput>
        <NButton type="primary" @click="search">查询</NButton>
      </NSpace>
    </div>

    <div>
      <NButton type="primary" @click="showadd">发贴</NButton>
    </div>

    <!-- 发布评论的对话框 -->
    <div>
      <div>
        <NModal v-model:show="visible" title="发贴">
          <NCard style="display: flex; justify-content: center; width: 70vw">
            <div>
              <NInput v-model:value="title" placeholder="标题"></NInput>
              <!-- <NInput type="textarea" v-model:value="info" placeholder="内容"></NInput> -->
              <div>富文本编辑器</div>
              <div style="border: 1px solid #ccc width=50vw; margin: 1rem auto">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
                />
                <Editor
                  style="height: 500px; overflow-y: hidden"
                  v-model="valueHtml"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
                />
              </div>

              <hr />
              <div>
                {{ valueHtml }}
              </div>
            </div>

            <template #action>
              <div style="text-align: right">
                <NButton type="primary" @click="addReply">发布</NButton>
              </div>
            </template>
          </NCard>
        </NModal>
      </div>
    </div>

    <HuangUserInfo></HuangUserInfo>
  </NEl>
  <div class="pl-20 pr-20" style="width: 50vw; margin: 0px auto">
    <!-- 切换排序 -->
    <NTabs @update:value="changeOrder">
      <NTabPane name="1" tab="最新"></NTabPane>
      <NTabPane name="2" tab="高赞"></NTabPane>
      <NTabPane name="3" tab="热门"></NTabPane>
      <NTabPane name="4" tab="热评"></NTabPane>
    </NTabs>
    <!-- 骨架屏效果 -->
    <div v-if="loading && firstLoad">
      <div v-for="i in 5" :key="i" class="ml-20 m-20 mb-2">
        <NCard>
          <NSkeleton text></NSkeleton>
          <NSkeleton text></NSkeleton>
          <div class="img-box">
            <NSkeleton class="vimg" text></NSkeleton>
            <NSkeleton class="vimg" text></NSkeleton>
            <NSkeleton class="vimg" text></NSkeleton>
          </div>
        </NCard>
      </div>
    </div>
    <!-- 数据列表 -->
    <div v-else>
      <div v-for="m in list" :key="m.mid" class="mb-3">
        <!-- 无图模式 -->
        <div>
          <NCard>
            <div>
              {{ m.user.user.username || m.user.info.nickname }}
            </div>
            <div @click="toDetail(m.mid)">{{ m.title }}</div>

            <div>
              <div class="detail" mb-2 mt-2>
                <div>{{ Tools.formatDate(m.lastupdate, 'yyyy-MM-dd') }} 点击量：{{ m.hits }}</div>
                <div>
                  <NPopover trigger="hover">
                    <Span>点赞量:{{ m.praise }}</Span>
                    <template #trigger>
                      <div @click="likeMessage(m)" :class="{ active: m.exInfo.praised }">赞</div>
                    </template>
                  </NPopover>
                </div>
                <div @click="showreport(m)">举报</div>
              </div>
            </div>
          </NCard>
        </div>
      </div>
    </div>
  </div>
  <div class="f-4 tc" v-if="loading">
    <span> <NSpin size="small"></NSpin>正在加载中... </span>
    <!-- <span><NSpin size="small"></NSpin>正在加载中... </span> -->
  </div>

  <div class="f-4 tc" v-if="page.pageNumber >= page.pageCount && !loading">到底了</div>

  <NBackTop></NBackTop>
</template>
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

// @ts-expect-error 引入报错
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import UserInfo from '@/components/UserInfo.vue'
import { ref, onMounted, onUnmounted, onBeforeUnmount, shallowRef } from 'vue'
import type { BaseResultData, PageBean, PageV0, BaseResult } from '@/types/BaseResult'
import { Api } from '@/types/Api'
import { Tools } from '@/types/Tools'
import { useRouter } from 'vue-router'
const router = useRouter()
import {
  useMessage,
  NCard,
  NSkeleton,
  NSpace,
  NPopover,
  NButton,
  NInput,
  NEl,
  NTabs,
  NTabPane,
  NBackTop,
  NModal,
} from 'naive-ui'
import type { TbMessageJoin } from '@/types/message'

const message = useMessage()

const loading = ref(false)

const firstload = ref(true)

//#region 查询的部分

const page = ref({ pageNumber: 1, pageSize: 10 } as PageBean)
const list = ref([] as TbMessageJoin[])
const queryInfo = ref({ order: 1, title: '' })

const query = () => {
  loading.value = true
  Api.get(
    `/message/${page.value.pageSize}/${page.value.pageNumber}/${queryInfo.value.order}`,
    { info: queryInfo.value.title },
    (data: BaseResultData<PageV0<TbMessageJoin>>) => {
      if (data.success) {
        // 数据为追加模式
        list.value = list.value.concat(data.data.list)
        page.value = data.data.pageBean
        firstload.value = false
        return
      }
      message.error(data.message)
    },
  )
}

const changeOrder = (order: number) => {
  queryInfo.value.order = order
  requery()
}

const search = () => {
  firstload.value = true
  page.value.pageNumber = 1
  list.value = []
  query()
}

const requery = () => {
  firstload.value = true
  page.value.pageNumber = 1
  queryInfo.value.title = ''
  list.value = []
  query()
}

const loadmore = () => {
  page.value.pageNumber++
  if (page.value.pageNumber > page.value.pageCount) {
    return
  }
  query()
}
//#region 滚动相关
const scroll = () => {
  // console.log('滚动了')

  if (loading.value) {
    return
  }
  // console.log("是否到达底部：",isScrollTobotton())
  if (isScrollTobotton()) {
    loadmore()
  }
}

const isScrollTobotton = () => {
  const scrollTop = document.documentElement.scrollTop || window.scrollY
  const clientHeight = document.documentElement.clientHeight
  const scrollHeight = document.documentElement.scrollHeight
  return scrollTop + clientHeight >= scrollHeight - 100
}
//#endregion

// #region 点赞相关
const likeMessage = (msg: TbMessageJoin) => {
  Api.post(`/message/praise/${msg.mid}`, {}, (data: BaseResultData<number>) => {
    if (data.success) {
      msg.exInfo.praised = !msg.exInfo.praised // 切换点赞状态
      msg.praise = msg.exInfo.praised ? msg.praise + 1 : msg.praise - 1
    } else {
      message.error(data.message)
    }
  })
}

//#endregion

//#region 举报帖子
const mid = ref<number | null>(null)

const pisible = ref(false)
const info = ref('')
const showreport = (msg: TbMessageJoin) => {
  mid.value = msg.mid
  info.value = ''
  pisible.value = true
}

// #region 举报

const report = () => {
  if (!mid.value) {
    message.error('帖子ID不存在')
    return
  }
  Api.post(`/report/message`, { mid: mid.value, info: info.value }, (data: BaseResult) => {
    if (data.success) {
      pisible.value = false
      message.success(data.message)
    } else {
      message.error(data.message)
    }
  })
}

// #endregion

//#endregion

//#region 发贴
const visible = ref(false)
// const info = ref('')
const title = ref('')
const showadd = () => {
  // info.value = ''
  title.value = ''
  visible.value = true
}

const addReply = () => {
  Api.post(`/message`, { info: valueHtml.value, title: title.value }, (data: BaseResult) => {
    loading.value = false
    if (data.success) {
      visible.value = false
      message.success(data.message)
    } else {
      message.error(data.message)
    }
  })
}

//#endregion

//#region 详情页
const toDetail = (mid: number) => {
  router.push(`/message/${mid}`)
}

onMounted(() => {
  requery()
  window.addEventListener('scroll', scroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', scroll)
})

const mode = ref('default')

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
  }, 1500)

  console.log('editorRef', editorRef.value, editorConfig)
})

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: Api.editorUrl(),
      fieldName: 'file',
      meta: {
        fileinfo: '富文本框上传图片',
      },
      // @ts-expect-error 引入报错
      customInsert(res, insertFn) {
        insertFn(Api.editorImageUrl(res.data.fid), '', Api.editorImageUrl(res.data.fid))
      },
    },
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// @ts-expect-error 引入报错
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>

<style scoped lang="scss">
.top-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  position: sticky;
  top: 0px;
  z-index: 10;
  background-color: var(--body-color);
}

.vimg {
  display: block;
  height: 7vh;
}

.img-box {
  display: flex;
  gap: 1rem;
  > div {
    flex: 1;
  }
  img {
    display: block;
    aspect-ratio: 16/9;
    width: 100%;
    object-fit: cover;
  }
}

.simg-box {
  display: flex;
  gap: 1rem;
  img {
    display: block;
    width: 100%;
    aspect-ratio: 19/9;
    object-fit: cover;
  }
  > div:first-of-type {
    flex: 2;
  }
  > div:last-of-type {
    flex: 1;
  }
  .info {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
  }
}

.detail {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .active {
    color: red;
  }
}
</style>
